package com.hanson.api;

import com.hanson.common.bean.ResultMessage;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.UserAddresBean;
import com.hanson.service.UserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api(tags = "用户地址管理")
@RestController
@RequestMapping("/api/address")
public class AddressApiController {
    @Autowired
    private UserAddressService userAddressService;

    @ApiOperation(value = "新增地址")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultMessage add(@RequestBody UserAddresBean userAddresBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        userAddressService.addAddress(openId, userAddresBean);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("新增地址成功！");
        return resultMessage;
    }

    @ApiOperation(value = "修改地址")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultMessage modify(@RequestBody UserAddresBean userAddresBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        userAddressService.updateAddress(openId, userAddresBean);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("修改地址成功！");
        return resultMessage;
    }

    @ApiOperation(value = "删除地址")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public ResultMessage delete(@PathVariable String id, HttpServletRequest request) throws Exception {
        userAddressService.deleteAddress(id);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("删除地址成功！");
        return resultMessage;
    }

    @ApiOperation(value = "设置某个地址是否是默认地址")
    @RequestMapping(value = "/updateIsDefault/{id}/{isDefault}", method = RequestMethod.POST)
    public ResultMessage updateIsDefault(HttpServletRequest request, @PathVariable String id, @PathVariable String isDefault) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        userAddressService.updateIsDefault(openId, isDefault, id);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setMsg("修改成功！");
        return resultMessage;
    }

    @ApiOperation(value = "获取用户地址列表")
    @RequestMapping(value = "/addressList", method = RequestMethod.GET)
    public ResultMessage addressList(HttpServletRequest request) {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(userAddressService.selectByOpenId(openId));
        return resultMessage;
    }

}
